﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vITs.Site.Models.ActionModels;
using vITs.Site.Models.DataModels;

namespace vITs.Site.Controllers
{
    public class VacationController : Controller
    {
        //
        // GET: /Vacation/

        [HttpGet]
        public ActionResult CreateVacation(int AssignmentId)
        {
            VitsDB db = new VitsDB();
            var assignment = db.Assignments.SingleOrDefault(a => a.AssignmentId == AssignmentId);

           if (assignment.Consultant.EmailAddress != this.User.Identity.Name)
           return RedirectToAction("../");

            ViewBag.assignment = assignment;

            ViewBag.Errors = TempData["error"];

            return View();
        }

        [HttpPost]
        public ActionResult CreateVacation(CreateVacationModel CVM, int AssignmentId)
        {
            VitsDB db = new VitsDB();
            var assignment = db.Assignments.SingleOrDefault(a => a.AssignmentId == AssignmentId);
            
            if (DateTime.Compare(assignment.StartDate, DateTime.Parse(CVM.StartDateVacation)) > 0 || DateTime.Compare(assignment.EndDate, DateTime.Parse(CVM.EndDateVacation)) < 0)
            {
                TempData["error"] = "Datumen du angav är utanför uppdragets datum";
                return RedirectToAction("CreateVacation", new { AssignmentId = assignment.AssignmentId });
            }
            else if (DateTime.Compare(DateTime.Parse(CVM.StartDateVacation), DateTime.Parse(CVM.EndDateVacation)) >= 0)
            {
                TempData["error"] = "Startdatumet du angav är senare eller samma dag som slutdatumet";
                return RedirectToAction("CreateVacation", new { AssignmentId = assignment.AssignmentId });
            }
            else
            {
                db.AddToBreaks(new Break() { EndDate = DateTime.Parse(CVM.EndDateVacation), StartDate = DateTime.Parse(CVM.StartDateVacation), AssignmentId = AssignmentId });

                db.SaveChanges();
                return RedirectToAction("ViewAssignment", "Consultant", new { AssignmentId = assignment.AssignmentId });
            }
        }
            
    }
}
